<!-- 消息框 -->
<template>
	<div class="message">
		<header class="header">
			<!-- <div v-if="selectedChat" class="flex items-center">
				<img :src="selectedChat.user.img" alt="" class="w-[35px] h-[35px] rounded-[50%] mr-[10px]" />
				<div>
					<div class="text-[#333333] text-[14px] mb-[6px]">
						{{ selectedChat.user.name }}
					</div>
					<div class="text-[#999999] text-[12px]">ID:{{ selectedChat.id }}</div>
				</div>
			</div> -->
			<el-form ref="queryForm" slot="header" :inline="true" :model="queryParams" label-width="75px">
			<el-form-item label="客服名称:" prop="userName">
				<el-input v-model.trim="queryParams.userName" clearable placeholder="请输入客服名称" @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="聊天内容:" prop="content">
				<el-input v-model.trim="queryParams.userName" clearable placeholder="请输入聊天内容" @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item>
				<l-search @search="handleQuery" @refresh="resetQuery" />
			</el-form-item>
		</el-form>
		</header>
		<div ref="messageWrapper" class="message-wrapper">
			<template v-if="selectedChat">
				<div class="pulldown-scroller">
					<div class="pulldown-wrapper">
						<div v-html="tipText"></div>
					</div>
					<ul>
						<li v-for="(item, index) in list" :key="index" class="message-item !py-[10px]">
							<div v-if="item.unreadStatus === 0" class="time">
								<span>{{ item.date | time }}</span>
							</div>
							<div class="main relative" :class="{ self: item.self }">
								<div class="flex" :style="{ flexDirection: item.self ? 'row-reverse' : '' }">
									<img class="avatar !w-[45px] !h-[45px] !rounded-[50%]" :src="item.photo" />
									<div>
										<div class="flex items-center text-sm mb-[5px]" :style="{ flexDirection: item.self ? 'row-reverse' : '' }">
											<span>{{ item.joinUserId }}</span>
											<div class="w-[10px]"></div>
											<span class="text-[#cccccc]">({{ item.date }})</span>
										</div>
										<div v-if="item.msgType === 0" class="content">
											<div class="text" v-html="replaceFace(item.content)"></div>
										</div>
										<div v-if="item.msgType === 1" class="content content-img">
											<div v-if="item.msgType === 1" class="text-img">
												<el-image class="img" :src="item.content" :preview-src-list="[item.content]"></el-image>
											</div>
										</div>
										<div v-if="item.msgType === 2" class="content content-audio">
											<div class="box">
												<audio class="audio" :src="item.content" controls="controls"></audio>
											</div>
										</div>
										<div v-if="item.msgType === 3" class="content content-video" @click="playVideo(item.content)">
											<video :src="item.content.split('?')[0]" playsinline></video>
											<img src="@/assets/images/play.png" alt="" />
										</div>
										<div v-if="item.msgType === 4" class="w-[244px] py-[7px] px-[12px] flex items-center bg-white rounded-[8px] mb-[5px]">
											<div class="w-[71px] h-[71px] mr-[12px]">
												<el-image class="w-full h-full rounded-[8px]" :src="item.content.picUrl" :preview-src-list="[]"> </el-image>
											</div>
											<div class="flex flex-col items-start" :style="{ width: 'calc(100% - 83px)' }">
												<div class="text-[#333333] text-[14px] truncate w-full text-left">{{ item.content.goodsName }}</div>
												<div class="text-[#CCCCCC] text-[12px] my-[8px]">销量{{ item.content.sales }}</div>
												<div class="flex items-baseline text-[#F14A46]"><span class="text-[12px]">￥</span><span class="text-[18px] font-bold">124.9</span></div>
											</div>
										</div>
									</div>
								</div>
								<div v-if="item.unreadStatus === 1 && item.self" class="text-[#999999] text-[12px] mt-[2px] pr-[75px]">已读</div>
							</div>
						</li>
					</ul>
				</div>
			</template>
		</div>
		<el-dialog title="视频预览" :visible.sync="dialogVisible" width="440px">
			<video-player ref="videoPlayer" style="'height:'+ videoHeight +'px;width:'+ videoWidth +'px'" class="vjs-custom-skin" :options="playerOptions" :playsinline="true"> </video-player>
		</el-dialog>
	</div>
</template>

<script>
import { mapGetters, mapState } from 'vuex';
import 'video.js/dist/video-js.css';
import { videoPlayer } from 'vue-video-player';
import dayjs from 'dayjs';
import BScroll from '@better-scroll/core';
import PullDown from '@better-scroll/pull-down';
import ScrollBar from '@better-scroll/scroll-bar';
import { getChatRecord } from '@/api/mall/chat';
import { formatDate } from '@/utils';
BScroll.use(PullDown);
BScroll.use(ScrollBar);
const TIME_BOUNCE = 800;
const THRESHOLD = 100;
const STOP = 50;
const REQUEST_TIME = 2000;
const PHASE = {
	moving: {
		enter: 'enter',
		leave: 'leave',
	},
	fetching: 'fetching',
	succeed: 'succeed',
};
const ARROW_BOTTOM =
	'<svg width="16" height="16" viewBox="0 0 512 512"><path fill="currentColor" d="M367.997 338.75l-95.998 95.997V17.503h-32v417.242l-95.996-95.995l-22.627 22.627L256 496l134.624-134.623l-22.627-22.627z"></path></svg>';
const ARROW_UP =
	'<svg width="16" height="16" viewBox="0 0 512 512"><path fill="currentColor" d="M390.624 150.625L256 16L121.376 150.625l22.628 22.627l95.997-95.998v417.982h32V77.257l95.995 95.995l22.628-22.627z"></path></svg>';
export default {
	components: {
		videoPlayer,
	},
	computed: {
		...mapGetters(['selectedChat', 'messages', 'emojis', 'selectId', 'pages']),
		...mapState(['user']),
		list() {
			return this.messages.map((item) => {
				if (item.msgType === 4 && typeof item.content === 'string') {
					item.content = JSON.parse(item.content);
				}
				return item;
			});
		},
	},
	filters: {
		time(date) {
			return dayjs(date).format('HH:mm');
		},
	},
	data() {
		return {
			isPullingDown: false,
			tipText: null,
			image: '',
			dialogVisible: false,
			height: 0,
			playerOptions: {
				playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
				autoplay: true, //如果true,浏览器准备好时开始回放。
				muted: false, // 默认情况下将会消除任何音频。
				loop: false, // 导致视频一结束就重新开始。
				preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
				language: 'zh-CN',
				// aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
				fluid: false, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
				sources: [
					{
						type: '', //这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
						src: '', //url地址
					},
				],
				// width: document.documentElement.clientWidth, //播放器宽度
				notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
				controlBar: {
					timeDivider: true,
					durationDisplay: true,
					remainingTimeDisplay: true,
					fullscreenToggle: true, //全屏按钮
				},
				width: 400,
				height: 0,
			},
			videoWidth: 0,
			videoHeight: 0,
			bscroll: null,
			params: {
				pageNum: 1,
				pageSize: 10,
			},
			queryParams: {
				userName: undefined,
				content: undefined,
			},
		};
	},
	watch: {
		selectId() {
			this.refresh();
		},
	},
	methods: {
		refresh(refresh = true) {
			this.$nextTick(() => {
				setTimeout(() => {
					if (!this.scroll) {
						this.initScroll();
					} else {
						this.bscroll.refresh();
					}
					if (this.bscroll && this.list.length > 0) {
						//滚动到最底部
						let Lis = this.$refs.messageWrapper.querySelectorAll('li');
						const last = Lis[Lis.length - 1];
						// this.height = last.offsetHeight;
						this.bscroll.scrollToElement(last, refresh ? 300 : 0);
					}
				}, 100);
			});
		},
		initScroll() {
			this.bscroll = new BScroll(this.$refs.messageWrapper, {
				scrollY: true,
				scrollbar: {
					scrollbarTrackClickable: true,
				},
				bounceTime: TIME_BOUNCE,
				useTransition: false,
				click: true,
				pullDownRefresh: {
					threshold: THRESHOLD,
					stop: STOP,
				},
			});
			this.bscroll.on('pullingDown', this.pullingDownHandler);
			this.bscroll.on('scroll', this.scrollHandler);
			this.bscroll.on('scrollEnd', () => {
				this.bscroll.refresh();
			});
			this.bscroll.on('enterThreshold', () => {
				this.setTipText(PHASE.moving.enter);
			});
			this.bscroll.on('leaveThreshold', () => {
				this.setTipText(PHASE.moving.leave);
			});
		},
		scrollHandler(pos) {
			console.log(pos.y);
		},
		async pullingDownHandler() {
			this.setTipText(PHASE.fetching);
			this.isPullingDown = true;
			await this.requestData();
			this.setTipText(PHASE.succeed);
			this.bscroll.finishPullDown();
			setTimeout(() => {
				this.bscroll.refresh();
			}, TIME_BOUNCE + 50);
		},
		async requestData() {
			if (this.params.pageNum >= this.pages) return;
			try {
				this.params.pageNum++;
				const newData = await this.ajaxGet();
				await this.$store.dispatch('chat/updateMessages', {
					messages: newData.concat(this.messages),
					id: this.selectId,
				});
			} catch (err) {
				console.log(err);
			}
		},
		ajaxGet() {
			return new Promise((resolve) => {
				setTimeout(() => {
					getChatRecord({
						uuid: this.selectId,
						current: this.params.pageNum,
						size: this.params.pageSize,
						time: formatDate(new Date()),
					}).then((res) => {
						this.isPullingDown = false;
						this.$store.dispatch('chat/updatePages', res.data.pages);
						resolve(
							res.data.records.reverse().map((item) => ({
								content: item.msg,
								date: item.sendTime,
								self: item.userId.length < 6,
								msgType: item.msgType,
								joinUserId: item.joinUserId,
								userId: item.userId,
								unreadStatus: item.unreadStatus,
								photo: item.photo || require('@/assets/images/tx_02.jpg'),
							}))
						);
					});
				}, REQUEST_TIME);
			});
		},
		setTipText(phase = PHASE.default) {
			const TEXTS_MAP = {
				enter: `${ARROW_BOTTOM} Pull down`,
				leave: `${ARROW_UP} Release`,
				fetching: 'Loading...',
				succeed: 'Refresh succeed',
			};
			this.tipText = TEXTS_MAP[phase];
		},
		playVideo(content) {
			this.videoSrc = content.split('?')[0];
			this.$set(this.playerOptions, 'sources', [{ src: this.videoSrc, type: '' }]);
			this.videoWidth = this.getQueryVariable(content, 'width');
			this.videoHeight = this.getQueryVariable(content, 'height');
			// this.$set(this.playerOptions,'width',this.videoWidth)
			this.$set(this.playerOptions, 'height', 400 * (this.videoHeight / this.videoWidth));
			this.dialogVisible = true;
			// $event.target.play()
		},
		getQueryVariable(url, variable) {
			var chats = url.split('?')[1];
			let arr = chats.split('&');
			for (var i = 0; i < arr.length; i++) {
				var pair = arr[i].split('=');
				if (pair[0] === variable) {
					console.log(pair[0]);
					return pair[1];
				}
			}
			return false;
		},
		replaceFace(con) {
			if (con && con.includes('/:')) {
				var emojis = this.emojis;
				for (var i = 0; i < emojis.length; i++) {
					let img = require('../../../../../../static/emoji/' + emojis[i].file);
					// con = con.replace(emojis[i].reg, '<img src="static/emoji/' + emojis[i].file +'"  alt="" style="vertical-align: middle; width: 24px; height: 24px" />');
					con = con.replace(emojis[i].reg, `<img src="${img}"  alt="" style="vertical-align: middle; width: 24px; height: 24px" />`);
				}

				return con;
			}
			return con;
		},
		getDaysBetween(dateString1, dateString2) {
			var startDate = Date.parse(dateString1);
			var endDate = Date.parse(dateString2);
			if (startDate > endDate) {
				return 0;
			}
			if (startDate === endDate) {
				return 1;
			}
			var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
			return days;
		},
	},
};
</script>

<style lang="scss" scoped>
.video-js .vjs-icon-placeholder {
	width: 100%;
	height: 100%;
	display: block;
}
ul {
	list-style: none;
}
.pulldown-wrapper {
	position: absolute;
	width: 100%;
	padding: 20px;
	box-sizing: border-box;
	transform: translateY(-100%) translateZ(0);
	text-align: center;
	color: #999;
}
.message {
	width: 100%;
	flex: 1;
	background: #f2f2f2;
	position: relative;
}

.message .header {
	min-height: 74px;
	padding: 20px 17px 0;
	background-color: #ffff;
	display: flex;
	align-items: center;
}

.message .message-wrapper {
	height: 604px;
	padding: 10px 15px 0;
	overflow: hidden;
	background-color: #ffff;
	border-top: 1px solid #f5f5f5;
}

.message .message-wrapper .message {
	margin-bottom: 15px;
}
.message-item {
	position: relative;
}

.message .message-wrapper .time {
	width: 100%;
	font-size: 12px;
	margin: 7px auto;
	display: flex;
	justify-content: center;
}

.message .message-wrapper .time span {
	display: inline-block;
	padding: 4px 6px;
	color: #fff;
	border-radius: 3px;
	background-color: #dcdcdc;
}
.message .message-wrapper .time2 {
	margin: 7px auto;
	width: 100%;
}
.message .message-wrapper .time2 span {
	padding: 4px 6px;
}

.message .message-wrapper .main .avatar {
	float: left;
	margin: 0 15px;
	border-radius: 3px;
	width: 42px;
	height: 42px;
}

.message .message-wrapper .main .content {
	display: inline-block;
	position: relative;
	padding: 6px 10px;
	max-width: 330px;
	min-height: 36px;
	line-height: 24px;
	box-sizing: border-box;
	font-size: 14px;
	text-align: left;
	word-break: break-all;
	background-color: #FFFFFF;
	border: 1px solid #333333;
	border-radius: 4px;

	&.content-video {
		background: transparent;
		padding: 0;
		cursor: pointer;
		position: relative;

		&::before {
			border: 0;
		}

		img {
			position: absolute;
			display: block;
			width: 30px;
			height: 30px;
			top: 50%;
			left: 50%;
			margin-left: -15px;
			margin-top: -15px;
		}

		video {
			width: 150px;
			//height: 100px;
		}
	}
	&.content-audio {
		//padding: 0;
		padding: 5px;
		//background: transparent;
		//.box{
		//  padding: 10px;
		//  background: #fff;
		//}
		audio {
			height: 40px;
			display: block;
		}
	}
	&.content-img {
		background: transparent;
		padding: 0;
		line-height: normal;

		&::before {
			border: 0;
		}

		.img {
			display: block;
			max-width: 150px;
		}
	}
}

// .message .message-wrapper .main .content:before {
// 	content: ' ';
// 	position: absolute;
// 	top: 12px;
// 	right: 100%;
// 	border: 6px solid transparent;
// 	border-right-color: #fafafa;
// }

.message .message-wrapper .self {
	text-align: right;
}

.message .message-wrapper .self .avatar {
	float: right;
	margin: 0 15px;
}

.message .message-wrapper .self .content {
	background-color: rgba(11, 164, 37, 0.46);
	border: none;
}

// .message .message-wrapper .self .content:before {
// 	right: -12px;
// 	vertical-align: middle;
// 	border-right-color: transparent;
// 	border-left-color: rgba(11, 164, 37, 0.46);
// }
</style>
